//
//  AnimationViewController.m
//  LaunchAnimationDemo
//
//  Created by TaiHuiTao on 16/8/12.
//  Copyright © 2016年 Lee2Go. All rights reserved.
//

#import "AnimationViewController.h"
#import <AVKit/AVKit.h>
@interface AnimationViewController ()
@property (nonatomic, strong) AVPlayerViewController *moviePlayer;
@property (strong,nonatomic) AVPlayerItem *item;
@property (strong,nonatomic) AVPlayer *player;
@end

@implementation AnimationViewController

- (void)setMoviePath:(NSString *)moviePath{
    _moviePath = [moviePath copy];
    // 停止之前的播放
    self.moviePlayer.view.backgroundColor = [UIColor whiteColor];
    self.moviePlayer.showsPlaybackControls = false;
    
    
    //设置本地视频路径;

    NSURL *url=[NSURL fileURLWithPath:moviePath];

    AVAsset *asset = [AVAsset assetWithURL:url];

    self.item=[AVPlayerItem playerItemWithAsset:asset];
    //设置AVPlayer中的AVPlayerItem
    self.player=[AVPlayer playerWithPlayerItem:self.item];
    // 设置播放的路径
    self.moviePlayer.player = self.player;
    //监听status属性，注意监听的是AVPlayerItem

    //设置监听函数，监听视频播放进度的变化，每播放一秒，回调此函数
        __weak __typeof(self) weakSelf = self;
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        //当前播放的时间
        NSTimeInterval current = CMTimeGetSeconds(time);
        //视频的总时间
        NSTimeInterval total = CMTimeGetSeconds(weakSelf.player.currentItem.duration);

        if(current - total == 0){
            //播放结束
          weakSelf.playFinished();
        }
        }];
   [self.moviePlayer.player play];
}


-(AVPlayerViewController *)moviePlayer{
    if (!_moviePlayer) {
        _moviePlayer = [[AVPlayerViewController alloc]init];
        //裁剪以自适应
        _moviePlayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        [_moviePlayer.view setFrame:self.view.bounds];
        [self.view addSubview:_moviePlayer.view];
    }
    return _moviePlayer;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
